package com.todo.biz.application.handler.linstener.linstener;


import com.todo.biz.application.entity.BizBaseRedisKeyUtil;
import com.todo.biz.application.handler.linstener.message.CounterMessage;
import com.todo.common.utils.TodoCommonUtils;
import com.todo.component.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author azhebuxing
 * @date 2024/5/8 14:18
 * @description
 */
@Slf4j
@Component
public class CounterCacheListener {

    @Resource
    private RedisService redisService;

    @EventListener
    public void counterInfoCache(CounterMessage message) {
        if (message == null) {
            return;
        }
        String bizCounterIdKey = BizBaseRedisKeyUtil.getBizCounterIdKey(message.getBusinessScene(), message.getCounterType(), TodoCommonUtils.getBucketByUserId(message.getUserId(), TodoCommonUtils.DEFAULT_BUCKET_SIZE_100));
        Boolean isMember = redisService.sIsMember(bizCounterIdKey, String.valueOf(message.getBusinessId()));
        if (isMember) {
            String bizCounterCountKey = BizBaseRedisKeyUtil.getBizCounterCountKey(message.getBusinessScene(), message.getCounterType(), message.getBusinessId());
            redisService.incr(bizCounterCountKey, message.getPlus());
        } else {
            String bizCounterCountKey = BizBaseRedisKeyUtil.getBizCounterCountKey(message.getBusinessScene(), message.getCounterType(), message.getBusinessId());
            redisService.incr(bizCounterCountKey, message.getPlus());
            redisService.sAdd(bizCounterIdKey, String.valueOf(message.getBusinessId()));
        }
    }
}

